import React, { Component, Fragment } from 'react';
import Todoitem from './Todoitem';

class Todolist extends Component {

  constructor(props) {
    super(props);
    this.state = {
      inputValue: '',
      list: ['English', 'React']
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleBtnClick = this.handleBtnClick.bind(this);
    this.handleItemDel = this.handleItemDel.bind(this);
  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor='insert_area'>insert : </label>
          <input
            id='insert_area' 
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
          <button
            onClick={this.handleBtnClick}
          >submit</button></div>
        <ul>
          {
            this.getTodoItem()
          }
        </ul>
      </Fragment>
    );
  }

  handleInputChange(e){
    const value = e.target.value;
    this.setState(() => ({
      inputValue:value
    }));
  }

  handleBtnClick(){
    this.setState((prevState) => ({
      list:[...prevState.list, this.state.inputValue],
      inputValue:''
    }));
  }

  handleItemDel(index){
    this.setState((prevState) => {
      let list = [...prevState.list];
      list.splice(index, 1);
      return ({
        list:list,
      });
    });
  }

  getTodoItem(){
    return this.state.list.map((item, index) => {
      return (
        <Todoitem 
          key={index} 
          index={index} 
          content={item} 
          handleItemDel={this.handleItemDel}
        />
      );
    })
  }
}

export default Todolist;